﻿namespace Home.Pipelines.Http
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net.Http;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;

    public class BidHttpMessageHandler : DelegatingHandler
    {
        private readonly object httpHeaders;

        public BidHttpMessageHandler(object httpHeaders)
        {
            this.httpHeaders = httpHeaders;
        }

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (this.httpHeaders != null)
            {
                var items = BidHttpHelper.ConvertObjectToHttpHeaders(this.httpHeaders);
                foreach (var item in items)
                {
                    if (item.Value == null)
                    {
                        continue;
                    }

                    var values = item.Value as IEnumerable<string>;
                    if (values != null)
                    {
                        request.Headers.Add(item.Key, values);
                        continue;
                    }

                    var value = item.Value.ToString();
                    if (string.IsNullOrEmpty(value))
                    {
                        continue;
                    }

                    request.Headers.Add(item.Key, value);
                }
            }

            return base.SendAsync(request, cancellationToken);
        }
    }
}
